const { app, BrowserWindow, ipcMain, Tray, Menu, dialog, clipboard } = require('electron');
const path = require('path')
const fs = require('fs');
let store;
// 创建存储实例用于保存常用路径和收藏
// 使用异步方式初始化 store
async function initStore() {
    const { default: Store } = await import('electron-store');
    store = new Store({
        defaults: {
            recentPaths: [],
            favorites: [],
            toDelete: [],
            likeFolderPath: null,    // 存储 like 文件夹路径
            deleteFolderPath: null    // 存储 delete 文件夹路径
        }
    });
}
require('@electron/remote/main').initialize()
// 将 win 声明为全局变量
let mainWindow
let floatingButton;
let tray = null;
// 创建浮动按钮
function createFloatingButton() {
    floatingButton = new BrowserWindow({
      width: 50,
      height: 50,
      x: 0, // 左侧位置
      y: 200, // 距离顶部位置
      frame: false, // 无边框
      transparent: true,  // 添加透明支持
      alwaysOnTop: true, // 始终置顶
      skipTaskbar: true, // 不在任务栏显示
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true  // 确保启用
      }
    });
  
    // 重要：为浮动按钮启用 remote
    require('@electron/remote/main').enable(floatingButton.webContents);

    floatingButton.loadFile('floatingButton.html');
  
    // 监听显示主窗口的事件
    ipcMain.on('show-main-window', () => {
      if (mainWindow) {
        mainWindow.show();
        // 可选：隐藏浮动按钮
        // floatingButton.hide();
      }
    });
  }
// 创建托盘
function createTray() {
    // 创建托盘图标
    tray = new Tray(path.join(__dirname, 'assets/icon.ico')); // 请确保有一个图标文件

    // 创建托盘菜单
    const contextMenu = Menu.buildFromTemplate([
        {
            label: '显示主窗口',
            click: () => {
                mainWindow.show();
                mainWindow.focus();
            }
        },
        {
            label: '最小化到托盘',
            click: () => {
                mainWindow.hide();
            }
        },
        { type: 'separator' },
        {
            label: '退出',
            click: () => {
                app.quit();
            }
        }
    ]);

    // 设置托盘提示文字
    tray.setToolTip('文件控制器');
    
    // 设置托盘上下文菜单
    tray.setContextMenu(contextMenu);
    
    // 点击托盘图标时显示主窗口
    tray.on('click', () => {
        if (mainWindow.isVisible()) {
            mainWindow.hide();
        } else {
            mainWindow.show();
            mainWindow.focus();
        }
    });
}
// 添加检查和创建文件夹的函数
// 添加新的 IPC 处理函数
ipcMain.handle('set-folder-paths', async () => {
    const result = await dialog.showOpenDialog(mainWindow, {
        properties: ['openDirectory'],
        title: '选择创建 Like 和 Delete 文件夹的位置'
    });

    if (!result.canceled && result.filePaths.length > 0) {
        const basePath = result.filePaths[0];
        const newLikePath = path.join(basePath, 'Like');
        const newDeletePath = path.join(basePath, 'Delete');

        try {
            // 创建文件夹（如果不存在）
            if (!fs.existsSync(newLikePath)) {
                fs.mkdirSync(newLikePath);
            }
            if (!fs.existsSync(newDeletePath)) {
                fs.mkdirSync(newDeletePath);
            }

            // 保存路径到 store
            store.set('likeFolderPath', newLikePath);
            store.set('deleteFolderPath', newDeletePath);

            await dialog.showMessageBox(mainWindow, {
                type: 'info',
                title: '创建成功',
                message: `已成功创建文件夹：\nLike: ${newLikePath}\nDelete: ${newDeletePath}`
            });

            return {
                likePath: newLikePath,
                deletePath: newDeletePath
            };
        } catch (error) {
            await dialog.showErrorBox('错误', `创建文件夹失败: ${error.message}`);
            return null;
        }
    }
    return null;
});
function createWindow () {
    // 将 win 改为 mainWindow
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        frame: false,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
            webSecurity: false, // 允许加载本地资源
            allowRunningInsecureContent: false,
        }
    })
    
    require('@electron/remote/main').enable(mainWindow.webContents)
    mainWindow.loadFile('index.html')

    // 监听窗口最大化/还原事件
    mainWindow.on('maximize', () => {
        mainWindow.webContents.send('window-state', true);
    });

    mainWindow.on('unmaximize', () => {
        mainWindow.webContents.send('window-state', false);
    });
    // 窗口关闭时的处理
    mainWindow.on('close', (event) => {
        // 如果不是真正的退出操作，则只是隐藏窗口
        if (!app.isQuitting) {
            event.preventDefault();
            mainWindow.hide();
            // 可选：显示通知
            new Notification({
                title: '提示',
                body: '应用程序已最小化到系统托盘'
            }).show();
        }
    });
    // 打开开发者工具
    // mainWindow.webContents.openDevTools()
}

// 应用程序准备就绪时
app.whenReady().then(async () => {
    await initStore();  // 等待 store 初始化
    createWindow();
    createTray();
});



// 添加获取视频文件的函数

// 处理扫描目录请求
ipcMain.on('scan-directory', async (event, dirPath) => {
    try {
        const files = await scanDirectory(dirPath);
        event.reply('scan-result', files);
    } catch (error) {
        event.reply('scan-result', { error: `扫描出错: ${error.message}` });
    }
});

// 扫描目录函数
async function scanDirectory(dirPath) {
    try {
        const items = await fs.promises.readdir(dirPath);
        const fileList = [];
        
        for (const item of items) {
            const fullPath = path.join(dirPath, item);
            const stats = await fs.promises.stat(fullPath);
            
            fileList.push({
                name: item,
                path: fullPath,
                isDirectory: stats.isDirectory(),
                size: stats.size,
                mtime: stats.mtime,
                ctime: stats.birthtime,
            });
        }
        
        return fileList;
    } catch (error) {
        throw new Error(`无法访问目录: ${error.message}`);
    }
}
// 修改扫描函数，专门用于查找重复文件
async function scanForDuplicates(dirPath) {
    try {
        const fileList = [];
        let scannedCount = 0;
        let totalItems = 0;
        
        // 首先计算总文件数
        async function countItems(currentPath) {
            const items = await fs.promises.readdir(currentPath);
            totalItems += items.length;
            
            for (const item of items) {
                const fullPath = path.join(currentPath, item);
                const stats = await fs.promises.stat(fullPath);
                if (stats.isDirectory()) {
                    await countItems(fullPath);
                }
            }
        }
        
        // 递归扫描函数
        async function scan(currentPath) {
            const items = await fs.promises.readdir(currentPath);
            
            for (const item of items) {
                const fullPath = path.join(currentPath, item);
                const stats = await fs.promises.stat(fullPath);
                
                scannedCount++;
                // 每50个文件发送一次进度更新
                if (scannedCount % 50 === 0) {
                    mainWindow.webContents.send('scan-progress', {
                        current: scannedCount,
                        total: totalItems,
                        status: '正在扫描文件...'
                    });
                }
                
                if (stats.isDirectory()) {
                    await scan(fullPath);
                } else {
                    fileList.push({
                        name: item,
                        path: fullPath,
                        isDirectory: false,
                        size: stats.size,
                        mtime: stats.mtime,
                        ctime: stats.birthtime,
                    });
                }
            }
        }
        
        // 先计算总数
        await countItems(dirPath);
        mainWindow.webContents.send('scan-start', { total: totalItems });
        
        // 开始扫描
        await scan(dirPath);
        
        // 对文件进行分组并找出重复项
        const fileGroups = new Map();
        fileList.forEach(file => {
            // 获取基础文件名（移除扩展名和分卷号）
            let baseName = file.name;
            // 处理分卷压缩文件 (.001, .002 等)
            baseName = baseName.replace(/\.\d+$/, '');
            // 处理常见压缩文件扩展名
            baseName = baseName.replace(/\.(7z|zip|rar|tar|gz)$/, '');
            // 移除其他扩展名
            baseName = baseName.replace(/\.[^/.]+$/, '');
            
            if (!fileGroups.has(baseName)) {
                fileGroups.set(baseName, []);
            }
            fileGroups.get(baseName).push(file);
        });
        
        // 过滤出重复的文件组
        const duplicates = Array.from(fileGroups.entries())
            .filter(([_, files]) => files.length > 1)
            .map(([baseName, files]) => ({
                baseName,
                files: files.sort((a, b) => a.name.localeCompare(b.name))
            }));
        
        // 发送完成消息和重复文件列表
        mainWindow.webContents.send('scan-complete', duplicates);
        return duplicates;
        
    } catch (error) {
        console.error('扫描错误:', error);
        mainWindow.webContents.send('scan-error', error.message);
        throw error;
    }
}

// 添加 IPC 处理程序
ipcMain.handle('find-duplicates', async (event, dirPath) => {
    try {
        return await scanForDuplicates(dirPath);
    } catch (error) {
        return { error: error.message };
    }
});

// 添加窗口控制处理
ipcMain.on('window-control', (event, command) => {
    const window = BrowserWindow.fromWebContents(event.sender);
    
    switch (command) {
        case 'minimize':
            window.minimize();
            break;
            
        case 'maximize':
            if (window.isMaximized()) {
                window.unmaximize();
            } else {
                window.maximize();
            }
            event.reply('window-state', window.isMaximized());
            break;
            
        case 'hide':
            mainWindow.hide(); // 隐藏主窗口
            if (!floatingButton) {
                createFloatingButton(); // 创建浮动按钮
            } else {
                floatingButton.show(); // 显示已存在的浮动按钮
            }
            break;
            
        case 'close':
            app.isQuitting = true;
            app.quit();
            break;
    }
});
// 在现有的 IPC 处理程序中添加以下代码
ipcMain.handle('store-get', (event, key) => {
    return store.get(key);
});
  
ipcMain.handle('store-set', (event, key, value) => {
    store.set(key, value);
});

// 创建通用右键菜单
function createGeneralContextMenu() {
    return Menu.buildFromTemplate([
        {
            label: '软件信息',
            click: () => {
                dialog.showMessageBox({
                    title: '软件信息',
                    message: '文件控制器',
                    detail: '版本: 1.1.2\n作者: 凹兔基\n描述: 文件管理工具'
                });
            }
        },
        { type: 'separator' },
        {
            label: '查找重复文件',
            click: () => {
                mainWindow.webContents.send('find-duplicates');
            }
        },
        {
            label: '常用路径',
            submenu: buildRecentPathsMenu()
        },
        {
            label: '收藏文件',
            click: () => {
                require('electron').shell.showItemInFolder(store.get('likeFolderPath'));
            }
        },
        {
            label: '待删除文件',
            click: () => {
                require('electron').shell.showItemInFolder(store.get('deleteFolderPath'));
            }
        }
    ]);
}
// 添加文件移动函数
async function moveFileToFolder(filePath, targetFolder) {
    try {
        const fileName = path.basename(filePath);
        const newPath = path.join(targetFolder, fileName);

        // 检查目标文件是否已存在
        if (fs.existsSync(newPath)) {
            const result = await dialog.showMessageBox(mainWindow, {
                type: 'question',
                buttons: ['覆盖', '取消'],
                title: '文件已存在',
                message: `文件 "${fileName}" 在目标文件夹中已存在，是否覆盖？`
            });
            
            if (result.response === 1) { // 用户选择取消
                return false;
            }
        }

        await fs.promises.copyFile(filePath, newPath);
        await fs.promises.unlink(filePath); // 删除原文件
        return true;
    } catch (error) {
        dialog.showErrorBox('错误', `移动文件失败: ${error.message}`);
        return false;
    }
}
// 创建文件右键菜单
function createFileContextMenu(filePath) {
    return Menu.buildFromTemplate([
        {
            label: '添加到收藏',
            click: async () => {
                // 直接发送消息到渲染进程，不再执行移动文件操作
                mainWindow.webContents.send('add-to-favorites', filePath);
            }
        },
        {
            label: '标记为删除',
            click: async () => {
                // 直接发送消息到渲染进程，不再执行移动文件操作
                mainWindow.webContents.send('mark-for-delete', filePath);
            }
        },
        { type: 'separator' },
        {
            label: '显示文件信息',
            click: () => {
                mainWindow.webContents.send('show-file-info', filePath);
            }
        },
        {
            label: '打开所在文件夹',
            click: () => {
                require('electron').shell.showItemInFolder(filePath);
            }
        }
    ]);
}
// 添加文件移动处理程序
ipcMain.handle('move-file', async (event, { filePath, targetFolder, type }) => {
    try {
        const fileName = path.basename(filePath);
        const newPath = path.join(targetFolder, fileName);

        // 检查目标文件是否已存在
        if (fs.existsSync(newPath)) {
            const result = await dialog.showMessageBox(mainWindow, {
                type: 'question',
                buttons: ['覆盖', '取消'],
                title: '文件已存在',
                message: `文件 "${fileName}" 在目标文件夹中已存在，是否覆盖？`
            });
            
            if (result.response === 1) { // 用户选择取消
                return false;
            }
        }

        // 移动文件
        await fs.promises.copyFile(filePath, newPath);
        await fs.promises.unlink(filePath); // 删除原文件

        // 更新相应的列表
        if (type === 'like') {
            const favorites = store.get('favorites', []);
            if (!favorites.includes(newPath)) {
                favorites.push(newPath);
                store.set('favorites', favorites);
            }
        } else if (type === 'delete') {
            const toDelete = store.get('toDelete', []);
            if (!toDelete.includes(newPath)) {
                toDelete.push(newPath);
                store.set('toDelete', toDelete);
            }
        }

        // 通知渲染进程文件已移动
        mainWindow.webContents.send('file-moved', {
            originalPath: filePath,
            newPath: newPath,
            type: type
        });

        return true;
    } catch (error) {
        await dialog.showErrorBox('错误', `移动文件失败: ${error.message}`);
        return false;
    }
});
// 构建最近路径菜单
function buildRecentPathsMenu() {
    const recentPaths = store.get('recentPaths', []);
    return recentPaths.slice(0, 5).map(path => ({
        label: path,
        click: () => {
            clipboard.writeText(path);
            mainWindow.webContents.send('path-copied', path);
        }
    }));
}

// 监听右键菜单请求
ipcMain.on('show-context-menu', (event, data) => {
    const { type, filePath } = data;
    const menu = type === 'file' && filePath ? 
        createFileContextMenu(filePath) : 
        createGeneralContextMenu();
    menu.popup();
});
// 添加 IPC 处理函数来获取文件夹路径
ipcMain.handle('get-folder-paths', () => {
    return {
        likePath: store.get('likeFolderPath'),
        deletePath: store.get('deleteFolderPath')
    };
});
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
// 修改应用程序退出处理
app.on('before-quit', () => {
    app.isQuitting = true;
});

// 处理 dock 点击事件 (macOS)
app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    } else {
        mainWindow.show();
    }
});

// 添加新的 IPC 监听器来处理路径更新
ipcMain.on('update-recent-paths', (event, newPath) => {
    let recentPaths = store.get('recentPaths', []);
    
    // 如果路径已存在，先移除它
    recentPaths = recentPaths.filter(path => path !== newPath);
    
    // 将新路径添加到开头
    recentPaths.unshift(newPath);
    
    // 只保留最近的5个路径
    recentPaths = recentPaths.slice(0, 5);
    
    // 更新存储
    store.set('recentPaths', recentPaths);
});